package com.bigevent.interceptors;

import com.bigevent.utils.JwtUtil;
import com.bigevent.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //响应完成后清除ThreadLocal对象，防止内存泄露
        ThreadLocalUtil.remove();
    }

    //拦截器，用于验证token，需要去注册这个拦截器
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        try{
            Map<String, Object> stringObjectMap = JwtUtil.parseToken(token);
            //从redis中获取相同的token
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            String redisToken = operations.get(stringObjectMap.get("username")+":"+stringObjectMap.get("id"));
            if(redisToken==null){
                //redis失效，报401
                throw new RuntimeException();
            }
            //把从token中解析的数据存到ThreadLocal类中，实现数据共享。
            ThreadLocalUtil.set(stringObjectMap);
            return true;
        }catch (Exception e){
            response.setStatus(401);
            return false;
        }
    }
}
